module config

use, intrinsic :: iso_fortran_env, only : stderr=>error_unit, compiler_version

use pathlib, only : expanduser, get_suffix, make_absolute
use phys_consts, only : wp

implicit none (type, external)
private
public :: read_configfile, gemini_cfg, get_compiler_vendor, expand_envvar

type :: gemini_cfg

!> basic simulation information (base)
integer, dimension(3) :: ymd0
real(wp) :: UTsec0, tdur, dtout
real(wp) :: activ(3)
real(wp) :: tcfl
real(wp) :: Teinf
integer :: potsolve,flagperiodic,flagoutput
logical :: nooutput = .false.
logical :: dryrun = .false.

!> file information (files)
character(:), allocatable :: infile,outdir,indatsize,indatgrid,indatfile,out_format, &
  fieldpointfile

character(:), allocatable :: git_revision

!> neutral atmospheric perturbations
integer :: flagdneu                           ! whether or not to include neutral perturbations from input files
character(:), allocatable :: sourcedir        ! where the neutral input files are located
integer :: interptype=0                       ! assumptions to be used when interpolating neutrals:  0-cartesian 2D, 1-axisymmetric 2D, 3 - cartesian 3D
real(wp) :: sourcemlat=0,sourcemlon=0         ! source latitude and longitude
real(wp) :: dtneu=0                           ! time step between neutral inputs
real(wp) :: dxn=0,drhon=0,dzn=0               ! dx,dy (or drho),dz for neutral inputs

!> preciptiation file inputs
integer :: flagprecfile                       ! whether or not we have precipitation input from a file
character(:), allocatable :: precdir          ! location of precipitation input data
real(wp) :: dtprec=0                          ! time step between precipitation inputs

!> electric field file inputs
integer :: flagE0file                         ! whether or not to have electric field file input
character(:), allocatable :: E0dir            ! location of electric field input data
real(wp) :: dtE0=0                            ! time step between electric field inputs

!> GLOW parameters
integer :: flagglow              ! whether or not to use glow to compute impact ionization
real(wp) :: dtglow, dtglowout    ! time step between GLOW updates and outputs for GLOW emissions

integer :: flag_fang=2008   !< configure Fang ionization model

!! parameters below this line can only be changed via the .nml input format
!> equatorial ionization anomaly
logical :: flagEIA=.false.       ! whether or not to include and equatorial ionization anomaly in simulation
real(wp) :: v0equator=10._wp      ! max vertical drift of plasma at equator for EIA

!> varying neutral atmosphere background
logical :: flagneuBG=.false.                ! whether or not to allow MSIS to be called to update neutral background
real(wp) :: dtneuBG=900._wp                  ! approximate time between MSIS calls
integer :: msis_version

!> background preciptation
real(wp) :: PhiWBG=1e-3_wp                      ! background total energy flux in mW/m^2
real(wp) :: W0BG=3e3_wp                      ! background characteristic energy for precipitation

!> parallel current calculations
logical :: flagJpar=.true.                  ! whether or not to compute parallel current (some simulation setups will give really poor results); code ignores this if potential is resolved along the field line since computing Jpar will not be prone to artifacts as it is in th EFL cases...

!> inertial capacitance
integer :: flagcap = 0           ! use inertial capacitance? 0 - set all to zero, 1 - use ionosphere to compute, 2 - add a magnetospheric part
real(wp) :: magcap=5._wp        ! value of integrated magnetospheric capacitance to use

!> type of diffusion solver to sue
integer :: diffsolvetype=2       ! 1 - first order backward Euler time stepping; 2 - 2nd order TRBDF2 diffusion solver

!> milestone output information (default to none, i.e. zero value)
integer :: mcadence=-1      ! value less than zero switches this off, > zero gives the cadence at which to perform milestone outputs (in terms of number of outputs per milestone)

!> gravitational drift terms
logical :: flaggravdrift=.false.

!> flag for lagrangian grid (assume drifting at E x B/B**2)
logical :: flaglagrangian=.false.

!> do we consider pressure terms in perp momentum equations
logical :: flagdiamagnetic=.false.

end type gemini_cfg

interface
module subroutine read_nml(cfg, verbose)
class(gemini_cfg), intent(inout) :: cfg
logical, intent(in), optional :: verbose
end subroutine read_nml

module subroutine read_ini(cfg)
class(gemini_cfg), intent(inout) :: cfg
end subroutine read_ini
end interface

contains

subroutine read_configfile(cfg, verbose)
!! READS THE INPUT CONFIGURATION FILE, ASSIGNS VARIABLES FOR FILENAMES, SIZES, ETC.

class(gemini_cfg), intent(inout) :: cfg
logical, intent(in), optional :: verbose

integer :: i, realbits, lxp, lyp
real(wp) :: NaN, glat, glon, xdist, ydist, alt_min, alt_max, alt_scale(4), Bincl, nmf, nme

character(:), allocatable :: suffix

!> READ CONFIG FILE FOR THIS SIMULATION
!! NOTE: Namelist file groups must be read in order they appear in the Namelist file, or End of File error occurs
suffix = get_suffix(cfg%infile)

select case (suffix)
case ('.nml')
  call read_nml(cfg, verbose)
case ('.ini')
  call read_ini(cfg)
case default
  error stop 'not sure how to read config file ' // cfg%infile
end select

end subroutine read_configfile

character(5) function get_compiler_vendor() result(vendor)

character(80) :: cvers
integer :: i, j
character(*), parameter :: vendors(2) = [character(5) :: "Intel", "GCC"]

cvers = compiler_version()

do j = 1,size(vendors)
  vendor = vendors(j)
  i = index(cvers, vendor)
  if (i > 0) exit
end do

if(vendor=="GCC") then
  vendor = "GNU"
elseif(i == 0) then
  vendor = ""
  write(stderr,'(A,/,A)') "could not determine compiler vendor from",cvers
end if

end function get_compiler_vendor

function expand_envvar(path, envvar) result(expanded)
!! replace @...@ string like metabuild system e.g. CMake, based on env var
!! this function REQUIRES:
!!
!! 1. envvar is a defined environment variable
!! 2. path contains a matching @envvar@ substring

character(:), allocatable :: expanded, substr
character(*), intent(in) :: path, envvar

integer :: i, L, istat
character(1000) :: buf

expanded = expanduser(path)

i = index(path, "@")
if (i < 1) return

substr = "@" // envvar // "@"
i = index(path, substr)
if (i < 1) return
!! this envvar is not in path, perhaps multiple calls to expand_envvar.
!! Should this be an error?

call get_environment_variable(envvar, buf, length=L, status=istat)
if (istat /= 0 .or. L < 1) error stop "config:expand_envvar: environment variable empty or not defined: " // envvar

expanded = path(1:i - 1) // trim(adjustl(buf)) // path(i + len(substr):len(path))

end function expand_envvar

end module config


C$Procedure SPKW03 ( SPK, write segment, type 3 )

      SUBROUTINE SPKW03 (  HANDLE,  BODY,    CENTER,  FRAME,
     .                     FIRST,   LAST,    SEGID,   INTLEN,
     .                     N,       POLYDG,  CDATA,   BTIME )

C$ Abstract
C
C     Write a type 3 segment to an SPK file.
C
C$ Disclaimer
C
C     THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE
C     CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S.
C     GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE
C     ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE
C     PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS"
C     TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY
C     WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A
C     PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC
C     SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE
C     SOFTWARE AND RELATED MATERIALS, HOWEVER USED.
C
C     IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA
C     BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT
C     LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND,
C     INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS,
C     REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE
C     REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY.
C
C     RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF
C     THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY
C     CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE
C     ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE.
C
C$ Required_Reading
C
C     NAIF_IDS
C     SPC
C     SPK
C
C$ Keywords
C
C     EPHEMERIS
C
C$ Declarations

      IMPLICIT NONE

      INCLUDE 'spk03.inc'

      INTEGER               HANDLE
      INTEGER               BODY
      INTEGER               CENTER
      CHARACTER*(*)         FRAME
      DOUBLE PRECISION      FIRST
      DOUBLE PRECISION      LAST
      CHARACTER*(*)         SEGID
      DOUBLE PRECISION      INTLEN
      INTEGER               N
      INTEGER               POLYDG
      DOUBLE PRECISION      CDATA (*)
      DOUBLE PRECISION      BTIME

C$ Brief_I/O
C
C     Variable  I/O  Description
C     --------  ---  --------------------------------------------------
C     MAXDEG     P   Maximum degree of Chebyshev expansions.
C     TOLSCL     P   Scale factor used to compute time bound tolerance.
C     HANDLE     I   Handle of SPK file open for writing.
C     BODY       I   NAIF code for ephemeris object.
C     CENTER     I   NAIF code for the center of motion of the body.
C     FRAME      I   Reference frame name.
C     FIRST      I   Start time of interval covered by segment.
C     LAST       I   End time of interval covered by segment.
C     SEGID      I   Segment identifier.
C     INTLEN     I   Length of time covered by record.
C     N          I   Number of records in segment.
C     POLYDG     I   Chebyshev polynomial degree.
C     CDATA      I   Array of Chebyshev coefficients.
C     BTIME      I   Begin time of first record.
C
C$ Detailed_Input
C
C     HANDLE         DAF handle of an SPK file to which a type 3 segment
C                    is to be added.  The SPK file must be open for
C                    writing.
C
C     BODY           NAIF integer code for an ephemeris object whose
C                    state relative to another body is described by the
C                    segment to be created.
C
C     CENTER         NAIF integer code for the center of motion of the
C                    object identified by BODY.
C
C     FRAME          NAIF name for a reference frame relative to which
C                    the state information for BODY is specified.
C
C     FIRST,
C     LAST           Start and stop times of the time interval over
C                    which the segment defines the state of body.
C
C     SEGID          Segment identifier.  An SPK segment identifier may
C                    contain up to 40 characters.
C
C     INTLEN         Length of time, in seconds, covered by each set of
C                    Chebyshev polynomial coefficients (each logical
C                    record).  Each set of Chebyshev coefficents must
C                    cover this fixed time interval, INTLEN.
C
C     N              Number of sets of Chebyshev polynomial coefficients
C                    for coordinates and their derivatives (number of
C                    logical records) to be stored in the segment.
C                    There is one set of Chebyshev coefficients for each
C                    time period.
C
C     POLYDG         Degree of each set of Chebyshev polynomials. POLYDG
C                    must not exceed MAXDEG (see Parameters below).
C
C     CDATA          Array containing all the sets of Chebyshev
C                    polynomial coefficients to be placed in the
C                    segment of the SPK file. The coefficients are
C                    stored in CDATA in order as follows:
C
C                       the (degree + 1) coefficients for the first
C                       coordinate of the first logical record
C
C                       the coefficients for the second coordinate
C
C                       the coefficients for the third coordinate
C
C                       the coefficients for the derivative with respect
C                       to time of the first coordinate
C
C                       the coefficients for the derivative with respect
C                       to time of the second coordinate
C
C                       the coefficients for the derivative with respect
C                       to time of the third coordinate
C
C                       the coefficients for the first coordinate for
C                       the second logical record, ...
C
C                       and so on.
C
C                    The logical data records are stored contiguously:
C
C                       +----------+
C                       | Record 1 |
C                       +----------+
C                       | Record 2 |
C                       +----------+
C                           ...
C                       +----------+
C                       | Record N |
C                       +----------+
C
C                    The contents of an individual record are:
C
C                       +--------------------------------------+
C                       | Coeff set for X position component   |
C                       +--------------------------------------+
C                       | Coeff set for Y position component   |
C                       +--------------------------------------+
C                       | Coeff set for Z position component   |
C                       +--------------------------------------+
C                       | Coeff set for X velocity component   |
C                       +--------------------------------------+
C                       | Coeff set for Y velocity component   |
C                       +--------------------------------------+
C                       | Coeff set for Z velocity component   |
C                       +--------------------------------------+
C
C                   Each coefficient set has the structure:
C
C                       +--------------------------------------+
C                       | Coefficient of T_0                   |
C                       +--------------------------------------+
C                       | Coefficient of T_1                   |
C                       +--------------------------------------+
C                                         ...
C                       +--------------------------------------+
C                       | Coefficient of T_POLYDG              |
C                       +--------------------------------------+
C
C                    Where T_n represents the Chebyshev polynomial
C                    of the first kind of degree n.
C
C
C     BTIME          Begin time (seconds past J2000 TDB) of first set
C                    of Chebyshev polynomial coefficients (first
C                    logical record).
C
C$ Detailed_Output
C
C     None.
C
C$ Parameters
C
C     See the include file spk03.inc for declarations of the
C     parameters described below.
C
C     TOLSCL         is a tolerance scale for coverage gap at endpoints
C                    of the segment coverage interval.
C
C     MAXDEG         is the maximum allowed degree of the input
C                    Chebyshev expansions.
C
C$ Exceptions
C
C     1)  If the number of sets of coefficients is not positive
C         SPICE(NUMCOEFFSNOTPOS) is signaled.
C
C     2)  If the interval length is not positive, SPICE(INTLENNOTPOS)
C         is signaled.
C
C     3)  If the name of the reference frame is not recognized,
C         SPICE(INVALIDREFFRAME) is signaled.
C
C     4)  If segment stop time is not greater then the begin time,
C         SPICE(BADDESCRTIMES) is signaled.
C
C     5)  If the start time of the first record exceeds the descriptor
C         begin time by more than a computed tolerance, or if the end
C         time of the last record precedes the descriptor end time by
C         more than a computed tolerance, the error SPICE(COVERAGEGAP)
C         is signaled. See the Parameters section above for a
C         description of the tolerance.
C
C     6)  If the input degree POLYDG is less than 0 or greater than
C         MAXDEG, the error SPICE(INVALIDDEGREE) is signaled.
C
C     7)  If the last non-blank character of SEGID occurs past index
C         40, or if SEGID contains any nonprintable characters, the
C         error will be diagnosed by a routine in the call tree of this
C         routine.
C
C$ Files
C
C     A new type 3 SPK segment is written to the SPK file attached
C     to HANDLE.
C
C$ Particulars
C
C     This routine writes an SPK type 3 data segment to the designated
C     SPK file, according to the format described in the SPK Required
C     Reading.
C
C     Each segment can contain data for only one target, central body,
C     and reference frame.  The Chebyshev polynomial degree and length
C     of time covered by each logical record are also fixed.  However,
C     an arbitrary number of logical records of Chebyshev polynomial
C     coefficients can be written in each segment. Minimizing the
C     number of segments in an SPK file will help optimize how the SPICE
C     system accesses the file.
C
C$ Examples
C
C     Suppose that you have sets of Chebyshev polynomial coefficients
C     in an array CDATA pertaining to the position of the moon (NAIF ID
C     = 301), relative to the Earth-moon barycenter (NAIF ID = 3), in
C     the J2000 reference frame, and want to put these into a type 2
C     segment in an existing SPK file.  The following code could be used
C     to add one new type 2 segment.  To add multiple segments, put the
C     call to SPKW02 in a loop.
C
C     C
C     C      First open the SPK file and get a handle for it.
C     C
C            CALL DAFOPW ( SPKNAM, HANDLE )
C
C     C
C     C      Create a segment identifier.
C     C
C            SEGID = 'MY_SAMPLE_SPK_TYPE_3_SEGMENT'
C
C     C
C     C      Write the segment.
C
C            SUBROUTINE SPKW03 ( HANDLE, 301,    3,      'J2000',
C          .                     FIRST,  LAST,   SEGID,  INTLEN,
C          .                     N,      POLYDG, CDATA,  BTIME )
C
C     C
C     C      Close the file.
C     C
C            CALL DAFCLS ( HANDLE )
C
C$ Restrictions
C
C     None.
C
C$ Literature_References
C
C     None.
C
C$ Author_and_Institution
C
C     K.S. Zukor (JPL)
C
C$ Version
C
C-    SPICELIB Version 2.0.0, 18-JAN-2014 (NJB)
C
C        Relaxed test on relationship between the time bounds of the
C        input record set (determined by BTIME, INTLEN, and N) and the
C        descriptor bounds FIRST and LAST. Now the descriptor bounds
C        may extend beyond the time bounds of the record set by a ratio
C        computed using the parameter TOLSCL (see Parameters above for
C        details). Added checks on input polynomial degree.
C
C-    SPICELIB Version 1.1.0, 30-OCT-2006 (BVS)
C
C        Removed restriction that the input reference frame should be
C        inertial by changing the routine that determines the frame ID
C        from the name from IRFNUM to NAMFRM.
C
C-    SPICELIB Version 1.0.1, 19-SEP-2006 (EDW)
C
C        Corrected typo in the section name ("Example" to "Examples").
C
C-    SPICELIB Version 1.0.0, 01-AUG-1995 (KSZ)
C
C-&

C$ Index_Entries
C
C     write spk type_3 data segment
C
C-&

C
C     SPICELIB functions
C
      LOGICAL               FAILED
      LOGICAL               RETURN

C
C     Local Parameters
C
C     DTYPE is the SPK data type.
C
      INTEGER               DTYPE
      PARAMETER           ( DTYPE   =   3 )
C
C     ND is the number of double precision components in an SPK
C     segment descriptor. SPK uses ND = 2.
C
      INTEGER               ND
      PARAMETER           ( ND      =   2 )
C
C     NI is the number of integer components in an SPK segment
C     descriptor. SPK uses NI = 6.
C
      INTEGER               NI
      PARAMETER           ( NI      =   6 )
C
C     NS is the size of a packed SPK segment descriptor.
C
      INTEGER               NS
      PARAMETER           ( NS      =   5 )
C
C     SIDLEN is the maximum number of characters allowed in an
C     SPK segment identifier.
C
      INTEGER               SIDLEN
      PARAMETER           ( SIDLEN  =  40 )

C
C     Local variables
C
      CHARACTER*(SIDLEN)    ETSTR
      CHARACTER*(SIDLEN)    NETSTR

      DOUBLE PRECISION      DCD   ( ND )
      DOUBLE PRECISION      DESCR ( NS )
      DOUBLE PRECISION      LTIME
      DOUBLE PRECISION      MID
      DOUBLE PRECISION      NUMREC
      DOUBLE PRECISION      RADIUS
      DOUBLE PRECISION      RSIZE
      DOUBLE PRECISION      TOL

      INTEGER               I
      INTEGER               ICD   ( NI )
      INTEGER               K
      INTEGER               NINREC
      INTEGER               REFCOD

C
C     Standard SPICE error handling.
C
      IF ( RETURN () ) THEN
         RETURN
      END IF

      CALL CHKIN ( 'SPKW03' )

C
C     The number of sets of coefficients must be positive.
C
      IF ( N .LE. 0 ) THEN

         CALL SETMSG ( 'The number of sets of coordinate'
     .   //            'coefficients is not positive. N = #.' )
         CALL ERRINT ( '#', N                                 )
         CALL SIGERR ( 'SPICE(NUMCOEFFSNOTPOS)'               )
         CALL CHKOUT ( 'SPKW03'                               )
         RETURN

      END IF

C
C     Make sure that the degree of the interpolating polynomials is
C     in range.
C
      IF (  ( POLYDG .LT. 0 ) .OR. ( POLYDG .GT. MAXDEG )  )  THEN

         CALL SETMSG ( 'The interpolating polynomials have degree #; '
     .   //            'the valid degree range is [0, #].'             )
         CALL ERRINT ( '#', POLYDG                                     )
         CALL ERRINT ( '#', MAXDEG                                     )
         CALL SIGERR ( 'SPICE(INVALIDDEGREE)'                          )
         CALL CHKOUT ( 'SPKW03'                                        )
         RETURN

      END IF

C
C    The interval length must be positive.
C
      IF ( INTLEN .LE. 0 ) THEN

         CALL SETMSG ( 'The interval length is not positive.'
     .   //            'N = #'                                )
         CALL ERRDP  ( '#', INTLEN                            )
         CALL SIGERR ( 'SPICE(INTLENNOTPOS)'                  )
         CALL CHKOUT ( 'SPKW03'                               )
         RETURN

      END IF

C
C     Get the NAIF integer code for the reference frame.
C
      CALL NAMFRM ( FRAME, REFCOD )

      IF ( REFCOD .EQ. 0 ) THEN

         CALL SETMSG ( 'The reference frame # is not supported.'   )
         CALL ERRCH  ( '#', FRAME                                  )
         CALL SIGERR ( 'SPICE(INVALIDREFFRAME)'                    )
         CALL CHKOUT ( 'SPKW03'                                    )
         RETURN

      END IF

C
C     The segment stop time must be greater than the begin time.
C
      IF ( FIRST .GT. LAST ) THEN

         CALL SETMSG ( 'The segment descriptor start time: # is ' //
     .                 'greater than the segment end time: #'      )
         CALL ETCAL  ( FIRST, ETSTR                                )
         CALL ERRCH  ( '#',   ETSTR                                )
         CALL ETCAL  ( LAST,  NETSTR                               )
         CALL ERRCH  ( '#',   NETSTR                               )
         CALL SIGERR ( 'SPICE(BADDESCRTIMES)'                      )
         CALL CHKOUT ( 'SPKW03'                                    )
         RETURN

      END IF

C
C     Compute the tolerance to use for descriptor time bound checks.
C
      TOL = TOLSCL * MAX( ABS(FIRST), ABS(LAST) )

      IF ( FIRST .LT. BTIME - TOL ) THEN

         CALL SETMSG ( 'The segment descriptor start time # is too '
     .   //            'much less than the beginning time of the  '
     .   //            'segment data # (in seconds past J2000: #). '
     .   //            'The difference is # seconds; the  '
     .   //            'tolerance is # seconds.'                     )
         CALL ETCAL  ( FIRST, ETSTR                                  )
         CALL ERRCH  ( '#',   ETSTR                                  )
         CALL ETCAL  ( BTIME, ETSTR                                  )
         CALL ERRCH  ( '#',   ETSTR                                  )
         CALL ERRDP  ( '#',   FIRST                                  )
         CALL ERRDP  ( '#',   BTIME-FIRST                            )
         CALL ERRDP  ( '#',   TOL                                    )
         CALL SIGERR ( 'SPICE(COVERAGEGAP)'                          )
         CALL CHKOUT ( 'SPKW03'                                      )
         RETURN

      END IF

C
C     The end time of the final record must be greater than or
C     equal to the end time of the segment.
C
      LTIME = BTIME  +  ( N * INTLEN )

      IF ( LAST .GT. LTIME + TOL ) THEN

         CALL SETMSG ( 'The segment descriptor end time # is too '
     .   //            'much greater than the end time of the segment '
     .   //            'data # (in seconds past J2000: #). The '
     .   //            'difference is # seconds; the tolerance is # '
     .   //            'seconds.'                                    )
         CALL ETCAL  ( LAST,  ETSTR                                  )
         CALL ERRCH  ( '#',   ETSTR                                  )
         CALL ETCAL  ( LTIME, ETSTR                                  )
         CALL ERRCH  ( '#',   ETSTR                                  )
         CALL ERRDP  ( '#',   LAST                                   )
         CALL ERRDP  ( '#',   LAST-LTIME                             )
         CALL ERRDP  ( '#',   TOL                                    )
         CALL SIGERR ( 'SPICE(COVERAGEGAP)'                          )
         CALL CHKOUT ( 'SPKW03'                                      )
         RETURN

      END IF

C
C     Now check the validity of the segment identifier.
C
      CALL CHCKID ( 'SPK segment identifier', SIDLEN, SEGID )

      IF ( FAILED() ) THEN
         CALL CHKOUT ( 'SPKW03' )
         RETURN
      END IF

C
C     Store the start and end times to be associated
C     with this segment.
C
      DCD(1) = FIRST
      DCD(2) = LAST

C
C     Create the integer portion of the descriptor.
C
      ICD(1) = BODY
      ICD(2) = CENTER
      ICD(3) = REFCOD
      ICD(4) = DTYPE

C
C     Pack the segment descriptor.
C
      CALL DAFPS ( ND, NI, DCD, ICD, DESCR )

C
C     Begin a new segment of SPK type 3 form:
C
C        Record 1
C        Record 2
C        ...
C        Record N
C        INIT       ( initial epoch of first record )
C        INTLEN     ( length of interval covered by each record )
C        RSIZE      ( number of data elements in each record )
C        N          ( number of records in segment )
C
C     Each record will have the form:
C
C        MID        ( midpoint of time interval )
C        RADIUS     ( radius of time interval )
C        X coefficients, Y coefficients, Z coefficients
C        X' coefficients, Y' coefficents, Z' coefficients
C
      CALL DAFBNA ( HANDLE, DESCR, SEGID )

C
C     Calculate the number of Chebyshev coefficients in a record.
C
      NINREC = (POLYDG + 1) * 6

C
C     Fill segment with N records of data.
C
      DO I = 1, N
C
C        Calculate the midpoint and radius of the time of each
C        record, and put that at the beginning of each record.
C
         RADIUS = INTLEN / 2
         MID    = BTIME + RADIUS + ( I - 1 ) * INTLEN

         CALL DAFADA ( MID,    1 )
         CALL DAFADA ( RADIUS, 1 )

C
C        Put one set of coefficients into the segment.
C
         K = 1 + ( I - 1 ) * NINREC

         CALL DAFADA ( CDATA(K), NINREC )

      END DO

C
C     Store the initial epoch of the first record.
C
      CALL DAFADA ( BTIME, 1 )

C
C     Store the length of interval covered by each record.
C
      CALL DAFADA ( INTLEN, 1 )

C
C     Store the size of each record (total number of array elements).
C
      RSIZE = 2 + NINREC
      CALL DAFADA ( RSIZE, 1 )

C
C     Store the number of records contained in the segment.
C
      NUMREC = N
      CALL DAFADA ( NUMREC, 1 )

C
C     End this segment.
C
      CALL DAFENA

      CALL CHKOUT ( 'SPKW03' )
      RETURN
      END


      module parm
      integer icalen
      real :: prf_bsn

      real, dimension (:), allocatable :: alph_e
      real, dimension (:), allocatable :: co_p, surlag, cdn, nperco
      real, dimension (:), allocatable :: cmn, phoskd, psp, sdnco

!!   change per JGA 8/31/2011 gsm for output.mgt
      real :: yield, burn_frlb, pst_kg, r2adj_bsn
      real :: yieldgrn, yieldbms, yieldtbr, yieldn, yieldp
      real :: hi_bms, hi_rsd, yieldrsd
!!    arrays for Landscape Transport Capacity 5/28/2009 nadia
      real, dimension (:), allocatable :: l_k1, l_k2, l_lambda, l_beta
      real, dimension (:), allocatable :: l_gama, l_harea, l_vleng
      real, dimension (:), allocatable :: l_vslope, l_ktc

!!    arrays for Biofilm variables
      real, dimension (:), allocatable :: biofilm_mumax, biofilm_kinv
      real, dimension (:), allocatable :: biofilm_klw, biofilm_kla
      real, dimension (:), allocatable :: biofilm_cdet, biofilm_bm

!!    new arrays for routing units
      real, dimension (:,:), allocatable :: hru_rufr, daru_km, ru_k
      real, dimension (:,:), allocatable :: ru_c, ru_eiq, ru_ovsl, ru_a
      real, dimension (:,:), allocatable :: ru_ovs, ru_ktc
      real, dimension (:), allocatable :: gwq_ru, qdayout
      integer, dimension (:), allocatable :: ils2, ils2flag
      integer :: iru, mru, irch, isub, idum, mhyd_bsn, ipest, ils_nofig
      integer :: mhru1
      integer, dimension (:), allocatable :: mhyd1 , irtun

!! septic variables for output.std
      real :: wshd_sepno3, wshd_sepnh3, wshd_seporgn, wshd_sepfon
      real :: wshd_seporgp, wshd_sepfop, wshd_sepsolp, wshd_sepbod
      real :: wshd_sepmm
      integer, dimension (:), allocatable :: isep_hru
!! septic variables for output.std
      real :: fixco, nfixmx, rsd_covco, vcrit, res_stlr_co
      real :: wshd_sw, wshd_snob, wshd_pndfr, wshd_pndv, wshd_pndsed
      real :: wshd_wetfr, wshd_resfr, wshd_resha, wshd_pndha, percop
      real :: wshd_fminp, wshd_ftotn, wshd_fnh3, wshd_fno3, wshd_forgn
      real :: wshd_forgp, wshd_ftotp, wshd_yldn, wshd_yldp, wshd_fixn
      real :: wshd_pup, wshd_wstrs, wshd_nstrs, wshd_pstrs, wshd_tstrs
      real :: wshd_astrs
      real :: wshd_hmn, wshd_rwn, wshd_hmp, wshd_rmn, wshd_dnit, ffcb
!GWP edits
      real :: swcexp
!end edits
      real :: wshd_rmp, wshd_voln, wshd_nitn, wshd_pas, wshd_pal, wdpq
      real :: wshd_plch, wshd_raino3, ressedc, basno3f, basorgnf, wof_p
      real :: wshd_pinlet, wshd_ptile
      real :: basminpf, basorgpf, sftmp, smtmp, smfmx, smfmn, wgpq
      real :: wshd_resv, wshd_ressed, basno3i, basorgni, basminpi, wdlpq
      real :: basorgpi, peakr, pndsedin, sw_excess, albday, wglpq, wdps
      real :: wtabelo, timp, tilep, wt_shall
      real :: sq_rto
      real :: tloss, inflpcp, snomlt, snofall, fixn, qtile, crk, latlyr
      real :: pndloss, wetloss,potloss, lpndloss, lwetloss
      real :: sedrch, fertn, sol_rd, cfertn, cfertp, sepday, bioday
      real :: sepcrk, sepcrktot, fertno3, fertnh3, fertorgn, fertsolp
      real :: fertorgp
      real :: fertp, grazn, grazp, soxy, qdfr, sdti, rtwtr, ressa, wgps
      real :: rttime, rchdep, rtevp, rttlc, da_km, resflwi, wdlps, wglps
      real :: resflwo, respcp, resev, ressep,ressedi,ressedo,dtot,wdprch
      real :: nperco_bsn,pperco_bsn,rsdco,phoskd_bsn,voltot
      real :: volcrmin, msk_x
      real :: uno3d, canev, usle, rcn, surlag_bsn,bactkdq,precipday,wdpf
      real :: thbact, wpq20, wlpq20, wps20, wlps20, bactrop, bactsedp
      real :: bactlchp, bactlchlp, enratio, wetpcp, pndpcp, wetsep, wgpf
      real :: pndsep, wetev, pndev, pndsedo, wetsedo, pndflwi, wetflwi
      real :: pndflwo, wetflwo, wetsedi, da_ha, twlwet, twlpnd, vpd
      real :: bactrolp, bactsedlp, evrch, evlai, pet_day, ep_day, wdlpf
      real :: snoev, sno3up, adj_pkr, n_updis,p_updis,nactfr,reactw
      real :: sdiegropq, sdiegrolpq, sdiegrops, sdiegrolps, es_day
      real :: sbactrop, sbactrolp, sbactsedp, sbactsedlp, ep_max, wof_lp
      real :: sbactlchp, sbactlchlp, psp_bsn, rchwtr, resuspst, setlpst
      real :: bsprev, bssprev, spadyo, spadyev, spadysp, spadyrfv
      real :: spadyosp
      real :: qday, usle_ei, al5, pndsedc, no3pcp, rcharea, volatpst
      real :: wetsedc, uobw, ubw, uobn, uobp, respesti, wglpf
      real :: snocovmx, snocov1, snocov2, rexp, rcor, lyrtile, lyrtilex
      real :: ai0, ai1, ai2, ai3, ai4, ai5, ai6, rhoq, tfact, sno50cov
      real :: mumax, lambda0, lambda1, lambda2, k_l, k_n, k_p, p_n
      real :: rnum1, autop, auton, etday, hmntl, rwntl, hmptl, rmn2tl
      real :: rmptl,wdntl,cmn_bsn,rmp1tl,roctl,gwseep,revapday,reswtr
      real :: bury, difus, reactb, solpesto, petmeas, wdlprch, wdpres
      real :: sorpesto, spcon_bsn, spexp_bsn, solpesti, sorpesti,wdlpres
      real :: snoprev, swprev, shallstp, deepstp, msk_co1, msk_co2
      real :: ressolpo, resorgno, resorgpo, resno3o, reschlao, resno2o
      real :: resnh3o, qdbank, potpcpmm, potevmm, potsepmm, potflwo
      real :: potsedo, pest_sol, trnsrch, wp20p_plt, bactminp, bactminlp
      real :: wp20lp_plt,cncoef,cdn_bsn,sdnco_bsn,bact_swf,bactmx,bactmin
      real :: chla_subco, tb_adj, cn_froz, dorm_hr, smxco
      real :: depimp_bsn, ddrain_bsn, tdrain_bsn, gdrain_bsn
      real :: rch_san, rch_sil, rch_cla, rch_sag, rch_lag, rch_gra

!!    declare mike van liew variables
      real :: hlife_ngw_bsn, ch_opco_bsn, ch_onco_bsn
      real :: bc1_bsn, bc2_bsn, bc3_bsn, bc4_bsn, rcn_sub_bsn, decr_min
      real :: anion_excl_bsn
!!    delcare mike van liew variables

!    Drainmod tile equations  01/2006
      real, dimension (:), allocatable :: wat_tbl,sol_swpwt
      real, dimension (:,:), allocatable :: vwt
	  real :: re_bsn, sdrain_bsn, sstmaxd_bsn
	  real :: drain_co_bsn, pc_bsn, latksatf_bsn
!    Drainmod tile equations  01/2006
      integer :: i_subhw, imgt, idlast, iwtr, ifrttyp, mo_atmo, mo_atmo1
      integer :: ifirstatmo, iyr_atmo, iyr_atmo1, matmo
      integer :: mrg, mch, mcr, mpdb, mcrdb, mfdb, mhru, mhyd, mfcst
      integer :: mnr, myr, mcut, mgr, msubo, mrcho, isubwq, ffcst
      integer :: nhru, isproj, mo, nbyr, immo, nrch, nres, irte, i_mo
      integer :: icode, ihout, inum1, inum2, inum3, inum4, wndsim, ihru
      integer :: inum5, inum6, inum7, inum8, icfac
      integer :: nrgage, ntgage, nrgfil, ntgfil, nrtot, nttot, mrech
      integer :: lao, igropt, npmx, irtpest, curyr, tmpsim, icrk, iihru
!    Drainmod tile equations  01/2006
	integer :: ismax, itdrn, iwtdn, iroutunit, ires_nut
!    Drainmod tile equations  01/2006
      integer :: mtil, mvaro, mrecd, idist, mudb, mrecm, mrecc, iclb
      integer :: mrecy, ipet, nyskip, ideg, ievent, slrsim, iopera
      integer :: id1, idaf, idal, leapyr, mo_chk, rhsim, mstdo
      integer :: ifirsts, ifirsth, ifirstw, nstot, nhtot, nwtot, icst
      integer :: ilog, i, iyr, itotr, iwq, iskip, scenario, ifirstpet
      integer :: itotb,itots,iprp,pcpsim,itoth,nd_30,iops,iphr,isto,isol
      integer :: iscen, fcstyr, fcstday, fcstcycles, subtot, ogen
      integer :: msub, mhruo, mres, mapp, mpst, mlyr, igen, iprint, iida
      integer :: fcstcnt, icn, ised_det, mtran, idtill, motot
      integer, dimension(100) :: ida_lup, iyr_lup
      integer :: no_lup, no_up, nostep
!  routing 5/3/2010 gsm per jga
! date
      character(len=8) :: date
      character(len=10) :: time
      character(len=5) :: zone
      character(len=80) :: prog
      character(len=13) :: slrfile, wndfile, rhfile, petfile, calfile
      character(len=13) :: atmofile, lucfile
      character(len=13) :: septdb
      character(len=13) :: dpd_file, wpd_file, rib_file, sfb_file,
     &                     lid_file
      integer, dimension (:), allocatable :: ifirstr, idg, ifirsthr
      integer, dimension (:), allocatable :: values, ndays
      integer, dimension (:), allocatable :: ndays_noleap, ndays_leap
!     apex/command output files
      integer :: mapex
      real, dimension (:), allocatable :: flodaya, seddaya, orgndaya
      real, dimension (:), allocatable :: orgpdaya, no3daya, minpdaya
      real, dimension (:), allocatable :: hi_targ, bio_targ, tnyld
      integer, dimension (:), allocatable :: idapa, iypa, ifirsta
      integer, dimension (:), allocatable :: mo_transb, mo_transe
      integer, dimension (:), allocatable :: ih_tran
!     apex/command output files
!  septic inputs
!! septic change added iseptic 1/28/09 gsm
      integer :: msdb, iseptic
      real, dimension (:), allocatable :: sptqs,percp
      real, dimension (:), allocatable :: sptbodconcs, spttssconcs
      real, dimension (:), allocatable :: spttnconcs, sptnh4concs
      real, dimension (:), allocatable :: sptno3concs, sptno2concs
      real, dimension (:), allocatable :: sptorgnconcs, spttpconcs
      real, dimension (:), allocatable :: sptminps, sptorgps
      real, dimension (:), allocatable :: sptfcolis ,failyr,qstemm
!! septic changes added 1/28/09 gsm
      real, dimension (:), allocatable :: bio_amn, bio_bod, biom,rbiom
      real, dimension (:), allocatable :: fcoli, bio_ntr, bz_perc
      real, dimension (:), allocatable :: plqm,sep_cap,bz_area
      real, dimension (:), allocatable :: bz_z, bz_thk,  bio_bd
!! carbon outputs for .hru file
      real, dimension (:), allocatable :: cmup_kgh, cmtot_kgh
!! carbon outputs for .hru file
      real, dimension (:), allocatable :: coeff_bod_dc, coeff_bod_conv
      real, dimension (:), allocatable :: coeff_fc1, coeff_fc2
      real, dimension (:), allocatable :: coeff_fecal, coeff_plq
      real, dimension (:), allocatable :: coeff_mrt, coeff_rsp
      real, dimension (:), allocatable :: coeff_slg1, coeff_slg2
      real, dimension (:), allocatable :: coeff_nitr, coeff_denitr
      real, dimension (:), allocatable :: coeff_pdistrb,coeff_solpslp
      real, dimension (:), allocatable :: coeff_solpintc,coeff_psorpmax
!! Septic system by Jaehak Jeong
      integer, dimension (:), allocatable :: i_sep,isep_typ
      integer, dimension (:), allocatable :: isep_opt,sep_tsincefail
      integer, dimension (:), allocatable :: isep_tfail,isep_iyr
      integer, dimension (:), allocatable :: sep_strm_dist,sep_den

 !!   change per JGA 9/8/2011 gsm for output.mgt
      real, dimension (:), allocatable :: sol_sumno3, sol_sumsolp
      real, dimension (:), allocatable :: strsw_sum, strstmp_sum
      real, dimension (:), allocatable :: strsn_sum, strsp_sum
      real, dimension (:), allocatable :: strsa_sum

!! New pothole variables
      real, dimension (:), allocatable :: spill_hru,tile_out,hru_in
      real, dimension (:), allocatable :: spill_precip,pot_seep
      real, dimension (:), allocatable :: pot_evap,pot_sedin
      real, dimension (:), allocatable :: pot_solp,pot_solpi
      real, dimension (:), allocatable :: pot_orgp,pot_orgpi
      real, dimension (:), allocatable :: pot_orgn,pot_orgni
      real, dimension (:), allocatable :: pot_mps,pot_mpsi
      real, dimension (:), allocatable :: pot_mpa,pot_mpai
      real, dimension (:), allocatable :: pot_no3i,precip_in
      real, dimension (:), allocatable :: tile_sedo,tile_no3o
      real, dimension (:), allocatable :: tile_solpo,tile_orgno
      real, dimension (:), allocatable :: tile_orgpo,tile_minpso
      real, dimension (:), allocatable :: tile_minpao
! output files
!!  added for binary files 3/25/09 gsm
      integer :: ia_b, ihumus, itemp, isnow
      integer, dimension (:), allocatable :: icolb,icolr,icolrsv,icols
      integer, dimension (:), allocatable :: ipdvar,ipdvab,ipdvas,ipdhru
      real, dimension (:), allocatable :: wshddayo,wshdmono,wshdyro
      real, dimension (:), allocatable :: wshdaao,fcstaao
      real, dimension (:,:), allocatable :: wpstdayo,wpstmono,wpstyro
      real, dimension (:,:), allocatable :: yldkg, bio_hv
      real, dimension (:,:), allocatable :: wpstaao,rchmono,rchyro
      real, dimension (:,:), allocatable :: rchaao,rchdy,hrumono,hruyro
      real, dimension (:,:), allocatable :: hruaao,submono,subyro,subaao
      real, dimension (:,:), allocatable :: resoutm,resouty,resouta
      real, dimension (:,:), allocatable :: wshd_aamon
      real, dimension (:,:), allocatable :: wtrmon,wtryr,wtraa
      real, dimension (:,:), allocatable :: sub_smfmx, sub_smfmn
      real, dimension (:,:,:), allocatable :: hrupstd,hrupsta,hrupstm
      real, dimension (:,:,:), allocatable :: hrupsty
! mrg = max number of rainfall/temperature gages
      integer, dimension (:), allocatable :: ifirstt,ifirstpcp
      integer, dimension (:), allocatable :: elevp,elevt
! mfcst = max number of forecast regions
      real, dimension (:,:), allocatable :: ftmpstdmn,ftmpmn,ftmpmx
      real, dimension (:,:), allocatable :: ftmpstdmx
      real, dimension (:,:,:), allocatable :: fpr_w,fpcp_stat
! mch = max number of channels
      real, dimension (:), allocatable :: flwin,flwout,bankst,ch_wi,ch_d
      real, dimension (:), allocatable :: ch_onco, ch_opco
      real, dimension (:), allocatable :: ch_orgn, ch_orgp
      real, dimension (:), allocatable :: drift,rch_dox,rch_bactp
      real, dimension (:), allocatable :: alpha_bnk,alpha_bnke
      real, dimension (:), allocatable :: disolvp,algae,sedst,rchstor
      real, dimension (:), allocatable :: organicn,organicp,chlora
      real, dimension (:), allocatable :: nitraten,nitriten,ch_li,ch_si

!      real, dimension (:), allocatable :: ch_cov,ch_di,ch_erod,ch_l2
!      real, dimension (:), allocatable :: ch_san, ch_sil, ch_cla, ch_veg
!      real, dimension (:), allocatable :: ch_rcur, ch_ss, ch_fpr, ch_eqn
!      real, dimension (:), allocatable :: ch_crht

!     Sediment parameters added by Balaji for the new routines

      real, dimension (:), allocatable :: ch_bnk_san, ch_bnk_sil
      real, dimension (:), allocatable :: ch_bnk_cla, ch_bnk_gra
      real, dimension (:), allocatable :: ch_bed_san, ch_bed_sil
      real, dimension (:), allocatable :: ch_bed_cla, ch_bed_gra
      real, dimension (:), allocatable :: depfp,depsanfp,depsilfp
      real, dimension (:), allocatable :: depclafp,depsagfp,deplagfp
      real, dimension (:), allocatable :: depch,depsanch,depsilch
      real, dimension (:), allocatable :: depclach,depsagch,deplagch
      real, dimension (:), allocatable :: depgrach,depgrafp,grast
      real, dimension (:), allocatable :: depprch,depprfp,prf,r2adj
      real, dimension (:), allocatable :: spcon, spexp
      real, dimension (:), allocatable :: sanst,silst,clast,sagst,lagst
      real, dimension (:), allocatable :: pot_san,pot_sil,pot_cla
      real, dimension (:), allocatable :: pot_sag,pot_lag
      real, dimension (:), allocatable :: potsani,potsili,potclai
      real, dimension (:), allocatable :: potsagi,potlagi
      real, dimension (:), allocatable :: sanyld,silyld,clayld,sagyld
      real, dimension (:), allocatable :: lagyld,grayld
      real, dimension (:), allocatable :: res_san,res_sil,res_cla
      real, dimension (:), allocatable :: res_sag,res_lag,res_gra
      real, dimension (:), allocatable :: pnd_san,pnd_sil,pnd_cla
      real, dimension (:), allocatable :: pnd_sag,pnd_lag
      real, dimension (:), allocatable :: wet_san,wet_sil,wet_cla
      real, dimension (:), allocatable :: wet_lag, wet_sag
      real :: ressano,ressilo,resclao,ressago,reslago, resgrao
      real :: ressani, ressili, resclai, ressagi, reslagi,resgrai
      real :: potsano,potsilo,potclao,potsago,potlago
	real :: pndsanin,pndsilin,pndclain,pndsagin,pndlagin
	real :: pndsano,pndsilo,pndclao,pndsago,pndlago

      real, dimension (:), allocatable :: ch_di,ch_erod,ch_l2, ch_cov
      real, dimension (:), allocatable :: ch_cov1, ch_cov2, ch_bnk_bd
      real, dimension (:), allocatable :: ch_bed_bd,ch_bnk_kd,ch_bed_kd
      real, dimension (:), allocatable :: ch_bnk_d50, ch_bed_d50
      real, dimension (:), allocatable :: tc_bed,tc_bnk
      integer, dimension (:), allocatable :: ch_eqn
      real, dimension (:), allocatable :: chpst_conc,chpst_rea,chpst_vol
      real, dimension (:), allocatable :: chpst_koc,chpst_stl,chpst_rsp
      real, dimension (:), allocatable :: chpst_mix,sedpst_conc,ch_wdr
      real, dimension (:), allocatable :: sedpst_rea,sedpst_bry
      real, dimension (:), allocatable :: sedpst_act,rch_cbod,rch_bactlp
      real, dimension (:), allocatable :: chside,rs1,rs2,rs3,rs4,rs5
      real, dimension (:), allocatable :: rs6,rs7,rk1,rk2,rk3,rk4,rk5
      real, dimension (:), allocatable :: rk6,bc1,bc2,bc3,bc4,ammonian
      real, dimension (:), allocatable :: orig_sedpstconc
      real, dimension (:,:), allocatable :: wurch
      integer, dimension (:), allocatable :: icanal
      integer, dimension (:), allocatable :: itb
! msub = max number of subbasins
      real, dimension (:), allocatable :: ch_revap, dep_chan
      real, dimension (:), allocatable :: harg_petco, subfr_nowtr
      real, dimension (:), allocatable :: cncoef_sub, dr_sub
      real, dimension (:), allocatable :: wcklsp,sub_fr,sub_minp,sub_sw
      real, dimension (:), allocatable :: sub_sumfc,sub_gwno3,sub_gwsolp
      real, dimension (:), allocatable :: sub_km,sub_tc,wlat,sub_pet,co2
      real, dimension (:), allocatable :: welev,sub_orgn,sub_orgp,sub_bd
      real, dimension (:), allocatable :: sub_wtmp,sub_sedpa,sub_sedps
      real, dimension (:), allocatable :: sub_minpa,sub_minps,daylmn
      real, dimension (:), allocatable :: latcos,latsin,phutot
      real, dimension (:), allocatable :: tlaps,plaps,tmp_an,sub_precip
      real, dimension (:), allocatable :: pcpdays, rcn_sub, rammo_sub
      real, dimension (:), allocatable :: atmo_day
      real, dimension (:), allocatable :: sub_snom,sub_qd,sub_sedy
      real, dimension (:), allocatable :: sub_tran,sub_no3,sub_latno3
      real, dimension (:,:), allocatable :: sub_smtmp,sub_timp,sub_sftmp
      real, dimension (:), allocatable :: sub_tileno3
      real, dimension (:), allocatable :: sub_solp,sub_subp,sub_etday
      real, dimension (:), allocatable :: sub_wyld,sub_surfq,sub_elev
      real, dimension (:), allocatable :: qird
      real, dimension (:), allocatable :: sub_gwq,sub_sep,sub_chl
      real, dimension (:), allocatable :: sub_cbod,sub_dox,sub_solpst
      real, dimension (:), allocatable :: sub_sorpst,sub_yorgn,sub_yorgp
      real, dimension (:), allocatable :: sub_bactp,sub_bactlp,sub_lat
      real, dimension (:), allocatable :: sub_latq, sub_gwq_d,sub_tileq
      real, dimension (:), allocatable :: sub_vaptile
      real, dimension (:), allocatable :: sub_dsan, sub_dsil, sub_dcla
      real, dimension (:), allocatable :: sub_dsag, sub_dlag

!!!!!! drains
      real :: vap_tile
      real, dimension (:), allocatable :: wnan
      real, dimension (:,:), allocatable :: sol_stpwt
      real, dimension (:,:), allocatable :: sub_pst,sub_hhqd,sub_hhwtmp
      real, dimension (:,:), allocatable :: rfinc,tmpinc,radinc,huminc
      real, dimension (:,:), allocatable :: wndav,ch_k,elevb,elevb_fr
      real, dimension (:,:), allocatable :: dewpt,ch_w,ch_s,ch_n
      real, dimension (:,:), allocatable :: amp_r,solarav,tmpstdmx
      real, dimension (:,:), allocatable :: tmpstdmn,pcf,tmpmn,tmpmx
      real, dimension (:,:), allocatable :: otmpstdmn,otmpmn,otmpmx
      real, dimension (:,:), allocatable :: otmpstdmx, ch_erodmo
      real, dimension (:,:), allocatable :: uh, hqdsave, hsdsave
      real, dimension (:,:,:), allocatable :: pr_w,pcp_stat
      real, dimension (:,:,:), allocatable :: opr_w,opcp_stat
      integer, dimension (:), allocatable :: hrutot,hru1,ireg
      integer, dimension (:), allocatable :: isgage,ihgage,iwgage
      integer, dimension (:), allocatable :: irgage,itgage,subgis
      integer, dimension (:), allocatable :: fcst_reg, irelh
! mlyr = max number of soil layers
      real, dimension (:,:), allocatable :: sol_aorgn,sol_tmp,sol_fon
      real, dimension (:,:), allocatable :: sol_awc,sol_prk,volcr
      real, dimension (:,:), allocatable :: pperco_sub
      real, dimension (:,:), allocatable :: sol_actp,sol_stap,conv_wt
      real, dimension (:,:), allocatable :: sol_solp,sol_ul,sol_fc,crdep
      real, dimension (:,:), allocatable :: sol_z,sol_up,sol_bd,sol_st
      real, dimension (:,:), allocatable :: flat,sol_nh3,sol_hk,sol_clay
!  added 1/27/09 when making septic changes
      real, dimension (:,:), allocatable :: sol_ec
!  added 1/27/09 when making septic changes
      real, dimension (:,:), allocatable :: sol_orgn,sol_por,sol_wp
      real, dimension (:,:), allocatable :: sol_orgp,sol_hum,sol_wpmm
      real, dimension (:,:), allocatable :: sol_k,sol_cbn,sol_no3
      real, dimension (:,:), allocatable :: sol_rsd,sol_fop
      real, dimension (:,:), allocatable :: sol_silt, sol_sand, sol_rock
      real, dimension (:,:), allocatable :: orig_solno3,orig_solorgn
      real, dimension (:,:), allocatable :: orig_solsolp,orig_solorgp
      real, dimension (:,:), allocatable :: orig_soltmp,orig_solrsd
      real, dimension (:,:), allocatable :: orig_solfop,orig_solfon
      real, dimension (:,:), allocatable :: orig_solaorgn,orig_solst
      real, dimension (:,:), allocatable :: orig_solactp,orig_solstap
      real, dimension (:,:), allocatable :: orig_volcr
!    Drainmod tile equations  01/2006
	  real, dimension (:,:), allocatable :: conk
!    Drainmod tile equations  01/2006
      real, dimension (:,:,:), allocatable :: sol_pst,sol_kp
      real, dimension (:,:,:), allocatable :: orig_solpst
! mres = max number of reservoirs
      real, dimension (:), allocatable :: velsetlr, velsetlp
      real, dimension (:), allocatable :: br1,res_k,lkpst_conc, evrsv
      real, dimension (:), allocatable :: res_evol,res_pvol,res_vol
      real, dimension (:), allocatable :: res_psa,lkpst_rea,lkpst_vol
      real, dimension (:), allocatable :: br2,res_rr,res_sed,lkpst_koc
      real, dimension (:), allocatable :: lkpst_stl,lkpst_rsp,lkpst_mix
      real, dimension (:), allocatable :: lkspst_conc,lkspst_rea
      real, dimension (:), allocatable :: theta_n, theta_p, con_nirr
      real, dimension (:), allocatable :: con_pirr
      real, dimension (:), allocatable :: lkspst_bry,lkspst_act,sed_stlr
      real, dimension (:), allocatable :: wurtnf,res_nsed,resdata,chlar
      real, dimension (:), allocatable :: res_orgn,res_orgp,res_no3
      real, dimension (:), allocatable :: res_solp,res_chla,res_seci
      real, dimension (:), allocatable :: res_esa,seccir,res_no2,res_nh3
      real, dimension (:), allocatable :: res_bactp, res_bactlp
      real, dimension (:), allocatable :: oflowmn_fps, starg_fps
      real, dimension (:), allocatable :: weirc, weirk, weirw
      real, dimension (:), allocatable :: acoef, bcoef, ccoef
      real, dimension (:), allocatable :: orig_resvol,orig_ressed
      real, dimension (:), allocatable :: orig_lkpstconc,orig_lkspstconc
      real, dimension (:), allocatable :: orig_ressolp,orig_resorgp
      real, dimension (:), allocatable :: orig_resno3,orig_resno2
      real, dimension (:), allocatable :: orig_resnh3,orig_resorgn
      real, dimension (:,:), allocatable :: starg,oflowmx,oflowmn
      real, dimension (:,:), allocatable :: psetlr,nsetlr,wuresn
      real, dimension (:,:,:), allocatable :: res_out
      integer, dimension (:), allocatable :: ires1,ires2,res_sub
      integer, dimension (:), allocatable :: iresco,mores,iyres
      integer, dimension (:), allocatable :: iflod1r,iflod2r,ndtargr
! mpdb = max number of pesticides in the database
      real, dimension (:), allocatable :: skoc,ap_ef,decay_f
      real, dimension (:), allocatable :: hlife_f,hlife_s,decay_s
      real, dimension (:), allocatable :: pst_wsol,pst_wof, irramt
      real, dimension (:), allocatable :: phusw, phusw_nocrop
      integer, dimension (:), allocatable :: nope, pstflg, nop
      integer, dimension (:), allocatable :: yr_skip, isweep
      integer, dimension (:), allocatable :: icrmx, nopmx
! new management scehduling variables
      integer, dimension (:,:), allocatable :: mgtop, idop
      integer, dimension (:,:), allocatable :: mgt1iop,mgt2iop,mgt3iop
      real, dimension (:,:), allocatable ::  mgt4op, mgt5op, mgt6op
      real, dimension (:,:), allocatable :: mgt7op, mgt8op, mgt9op
      real, dimension (:,:), allocatable :: mgt10iop, phu_op
! mcrdb = maximum number of crops in database
      real, dimension (:), allocatable :: wac21,wac22,cnyld,rsdco_pl
      real, dimension (:), allocatable :: wsyf,leaf1,leaf2,alai_min
      real, dimension (:), allocatable :: t_base,t_opt,hvsti,bio_e
      real, dimension (:), allocatable :: vpd2,gsi,chtmx,wavp,cvm
      real, dimension (:), allocatable :: blai,dlai,rdmx,cpyld,bio_leaf
      real, dimension (:), allocatable :: bio_n1,bio_n2,bio_p1,bio_p2
      real, dimension (:), allocatable :: bmx_trees,ext_coef,bm_dieoff
      real, dimension (:), allocatable :: rsr1, rsr2
!     real, dimension (:), allocatable :: air_str
      real, dimension (:,:), allocatable :: pltnfr,pltpfr
      integer, dimension (:), allocatable :: idc, mat_yrs
! mfdb = maximum number of fertilizer in database
      real, dimension (:), allocatable :: forgn,forgp,fminn,bactpdb
      real, dimension (:), allocatable :: fminp,fnh3n,bactlpdb,bactkddb
      character(len=8), dimension (200) :: fertnm
! mudb = maximum number of land types in urban database
      real, dimension (:), allocatable :: fimp,curbden,urbcoef,dirtmx
      real, dimension (:), allocatable :: thalf,tnconc,tpconc,tno3conc
      real, dimension (:), allocatable :: fcimp,urbcn2
! mapp = max number of applications
      real :: sweepeff,frt_kg, pst_dep
!! added pst_dep to statement below 3/31/08 gsm
!!   burn 3/5/09
! mnr = max number years of rotation
!!   burn 3/5/09
! mtil = max number tillages in database
 !! drainmod tile equations   06/2006

      real, dimension (:), allocatable :: ranrns_hru
	  integer, dimension (:), allocatable :: itill
!! drainmod tile equations   06/2006
      real, dimension (:), allocatable :: effmix,deptil, ranrns
      character(len=8), dimension (550) :: tillnm
! mhyd = max number of hydrograph nodes
      real, dimension (:), allocatable :: rnum1s,hyd_dakm
      real, dimension (:,:), allocatable :: varoute,shyd, vartran
      real, dimension (:,:,:), allocatable :: hhvaroute
      integer, dimension (:), allocatable :: icodes,ihouts,inum1s
      integer, dimension (:), allocatable :: inum2s,inum3s,inum4s
      integer, dimension (:), allocatable :: inum5s,inum6s,inum7s,inum8s
      integer, dimension (:), allocatable :: subed
      character(len=10), dimension (:), allocatable :: recmonps
      character(len=10), dimension (:), allocatable :: reccnstps
      character(len=5), dimension (:), allocatable :: subnum
      character(len=4), dimension (:), allocatable :: hruno

! mhru = maximum number of hydrologic response units
      real, dimension (:), allocatable :: grwat_n, grwat_i, grwat_l
      real, dimension (:), allocatable :: grwat_w, grwat_d
      real, dimension (:), allocatable :: grwat_s, grwat_spcon
      real, dimension (:), allocatable :: tc_gwat
      real, dimension (:), allocatable ::pot_volmm,pot_tilemm,pot_volxmm  !!NUBZ
      real, dimension (:), allocatable :: pot_fr,pot_tile,pot_vol,potsa
      real, dimension (:), allocatable :: pot_volx,potflwi,potsedi,wfsh
      real, dimension (:), allocatable :: pot_nsed,pot_no3l,newrti,gwno3
      real, dimension (:), allocatable :: pot_sed,pot_no3,fsred,tmpavp
      real, dimension (:), allocatable :: evpot, dis_stream, pot_solpl
      real, dimension (:), allocatable :: sed_con, orgn_con, orgp_con
      real, dimension (:), allocatable :: soln_con, solp_con, pot_k
      real, dimension (:), allocatable :: n_reduc, n_lag, n_ln, n_lnco
      integer, dimension (:), allocatable :: ioper
      integer, dimension (:), allocatable :: ngrwat
      real, dimension (:), allocatable :: filterw,sumix,usle_ls,phuacc
      real, dimension (:), allocatable :: esco,epco,slsubbsn,hru_slp
      real, dimension (:), allocatable :: erorgn,erorgp,biomix,pnd_seci
      real, dimension (:), allocatable :: flowmin,divmax,canmx,usle_p
      real, dimension (:), allocatable :: lat_sed,rch_dakm,pnd_no3s,cn1
      real, dimension (:), allocatable :: cn2,lat_ttime,flowfr,sol_zmx
      real, dimension (:), allocatable :: tile_ttime
      real, dimension (:), allocatable :: slsoil,sed_stl,gwminp,sol_cov
      real, dimension (:), allocatable :: yldanu,pnd_solp,pnd_no3,ov_n
      real, dimension (:), allocatable :: driftco,pnd_orgp,pnd_orgn,cn3
      real, dimension (:), allocatable :: sol_sumul,pnd_chla,hru_fr
      real, dimension (:), allocatable :: bio_ms,sol_alb,strsw,hru_km
      real, dimension (:), allocatable :: pnd_fr,pnd_psa,pnd_pvol,pnd_k
      real, dimension (:), allocatable :: pnd_esa,pnd_evol,pnd_vol,yldaa
      real, dimension (:), allocatable :: pnd_sed,pnd_nsed,strsa,dep_imp
      real, dimension (:), allocatable :: evpnd, evwet
      real, dimension (:), allocatable :: wet_fr,wet_nsa,wet_nvol,wet_k
      integer, dimension (:), allocatable :: iwetgw, iwetile
      real, dimension (:), allocatable :: wet_mxsa,wet_mxvol,wet_vol
      real, dimension (:), allocatable :: wet_sed,wet_nsed
      real, dimension (:), allocatable :: smx,sci,bp1,bp2
      real, dimension (:), allocatable :: bw1,bw2,bactpq
      real, dimension (:), allocatable :: bactp_plt,bactlp_plt,cnday
      real, dimension (:), allocatable :: bactlpq,auto_eff,sol_sw,secciw
      real, dimension (:), allocatable :: bactps,bactlps,tmpav,chlaw
      real, dimension (:), allocatable :: subp,sno_hru,hru_ra,wet_orgn
      real, dimension (:), allocatable :: tmx,tmn,rsdin,tmp_hi,tmp_lo
      real, dimension (:), allocatable :: rwt,olai,usle_k,tconc,hru_rmx
      real, dimension (:), allocatable :: usle_cfac,usle_eifac
      real, dimension (:), allocatable :: anano3,aird,t_ov,sol_sumfc
      real, dimension (:), allocatable :: sol_avpor,usle_mult,wet_orgp
      real, dimension (:), allocatable :: aairr,cht,u10,rhd
      real, dimension (:), allocatable :: shallirr,deepirr,lai_aamx
      real, dimension (:), allocatable :: canstor,ovrlnd,ch_l1,wet_no3
      real, dimension (:), allocatable :: irr_mx, auto_wstr
      real, dimension (:), allocatable :: cfrt_id, cfrt_kg, cpst_id
      real, dimension (:), allocatable :: cpst_kg
      real, dimension (:), allocatable :: irr_asq, irr_eff
      real, dimension (:), allocatable :: irrsq, irrefm, irrsalt
      real, dimension (:), allocatable :: bio_eat, bio_trmp             !!NUBZ
      integer, dimension (:), allocatable :: ifrt_freq,ipst_freq,irr_noa
      integer, dimension (:), allocatable :: irr_sc,irr_no
      integer, dimension (:), allocatable :: imp_trig, fert_days,irr_sca
      integer, dimension (:), allocatable :: pest_days, idplt, wstrs_id
      real, dimension (:,:), allocatable :: bio_aahv
!    Drainmod tile equations  08/2006
	  real, dimension (:), allocatable :: cumei,cumeira
	  real, dimension (:), allocatable :: cumrt, cumrai
!    Drainmod tile equations  08/2006
      real, dimension (:), allocatable :: wet_solp,wet_no3s,wet_chla
      real, dimension (:), allocatable :: wet_seci,pnd_no3g,pstsol
      real, dimension (:), allocatable :: gwht,delay,gw_q,pnd_solpg
      real, dimension (:), allocatable :: alpha_bf,alpha_bfe,gw_spyld
      real, dimension (:), allocatable :: alpha_bf_d,alpha_bfe_d
      real, dimension (:), allocatable :: gw_qdeep
      real, dimension (:), allocatable :: gw_delaye,gw_revap,rchrg_dp
      real, dimension (:), allocatable :: revapmn,anion_excl,rchrg
      real, dimension (:), allocatable :: ffc,bio_min,surqsolp
      real, dimension (:), allocatable :: cklsp,deepst,shallst,wet_solpg
      real, dimension (:), allocatable :: rchrg_src
      real, dimension (:), allocatable :: wet_no3g,sol_avbd,trapeff
      real, dimension (:), allocatable :: gwqmn,tdrain,pplnt,snotmp
      real, dimension (:), allocatable :: ddrain,gdrain,sol_crk,dayl,brt
!    Drainmod tile equations  01/2006
	real, dimension (:), allocatable ::ddrain_hru,re,sdrain,sstmaxd
	real, dimension (:), allocatable :: stmaxd,drain_co,pc,latksatf
!    Drainmod tile equations  01/2006
      real, dimension (:), allocatable :: twash,rnd2,rnd3,sol_cnsw,doxq
      real, dimension (:), allocatable :: rnd8,rnd9,percn,sol_sumwp
      real, dimension (:), allocatable :: tauton,tautop,cbodu,chl_a,qdr
      real, dimension (:), allocatable :: tfertn,tfertp,tgrazn,tgrazp
      real, dimension (:), allocatable :: latno3,latq,minpgw,no3gw,nplnt
      real, dimension (:), allocatable :: tileq, tileno3
      real, dimension (:), allocatable :: sedminpa,sedminps,sedorgn
      real, dimension (:), allocatable :: sedorgp,sedyld,sepbtm,strsn
      real, dimension (:), allocatable :: strsp,strstmp,surfq,surqno3
      real, dimension (:), allocatable :: tcfrtn,tcfrtp,hru_ha,hru_dafr
      real, dimension (:), allocatable :: drydep_no3, drydep_nh4
      real, dimension (:), allocatable :: phubase,bio_yrms,hvstiadj
      real, dimension (:), allocatable :: laimxfr,laiday,chlap,pnd_psed
      real, dimension (:), allocatable :: wet_psed,seccip,plantn,plt_et
      real, dimension (:), allocatable :: plt_pet,plantp,bio_aams
      real, dimension (:), allocatable :: bio_aamx,lai_yrmx,dormhr
      real, dimension (:), allocatable :: lat_pst
      real, dimension (:), allocatable :: orig_snohru,orig_potvol,fld_fr
      real, dimension (:), allocatable :: orig_alai,orig_bioms,pltfr_n
      real, dimension (:), allocatable :: orig_phuacc,orig_sumix,pltfr_p
      real, dimension (:), allocatable :: orig_phu, phu_plt
      real, dimension (:), allocatable :: orig_shallst,orig_deepst
      real, dimension (:), allocatable :: orig_pndvol,orig_pndsed,rip_fr
      real, dimension (:), allocatable :: orig_pndno3,orig_pndsolp
      real, dimension (:), allocatable :: orig_pndorgn,orig_pndorgp
      real, dimension (:), allocatable :: orig_wetvol,orig_wetsed
      real, dimension (:), allocatable :: orig_wetno3,orig_wetsolp
      real, dimension (:), allocatable :: orig_wetorgn,orig_wetorgp
      real, dimension (:), allocatable :: orig_solcov,orig_solsw
      real, dimension (:), allocatable :: orig_potno3,orig_potsed
      real, dimension (:), allocatable :: wtab,wtab_mn,wtab_mx
      real, dimension (:), allocatable :: shallst_n,gw_nloss,rchrg_n
      real, dimension (:), allocatable :: det_san, det_sil, det_cla
      real, dimension (:), allocatable :: det_sag, det_lag
      real, dimension (:), allocatable :: tnylda, afrt_surface
      real :: frt_surface
      real, dimension (:), allocatable :: auto_nyr, auto_napp
      real, dimension (:), allocatable :: manure_kg, auto_nstrs
      real, dimension (:,:), allocatable :: rcn_mo, rammo_mo
      real, dimension (:,:), allocatable :: drydep_no3_mo, drydep_nh4_mo
      real, dimension (:), allocatable :: rcn_d, rammo_d
      real, dimension (:), allocatable :: drydep_no3_d, drydep_nh4_d
      real, dimension (:,:), allocatable :: yldn
      real, dimension (:,:), allocatable :: gwati, gwatn, gwatl
      real, dimension (:,:), allocatable :: gwatw, gwatd, gwatveg
      real, dimension (:,:), allocatable :: gwata, gwats, gwatspcon
      real, dimension (:,:), allocatable :: rfqeo_30d,eo_30d
      real, dimension (:,:), allocatable :: wgncur,wgnold,wrt,psetlp
      real, dimension (:,:), allocatable :: zdb,pst_surq,pst_enr
      real, dimension (:,:), allocatable :: plt_pst,pst_sed,psetlw
      real, dimension (:,:), allocatable :: pcpband,wupnd,tavband,phi
      real, dimension (:,:), allocatable :: wat_phi
      real, dimension (:,:), allocatable :: wushal,wudeep,tmnband,snoeb
      real, dimension (:,:), allocatable :: nsetlw,snotmpeb,bss,surf_bs
      real, dimension (:,:), allocatable :: tmxband,nsetlp
      real, dimension (:,:), allocatable :: rainsub,frad
      real, dimension (:),   allocatable ::  rstpbsb
      real, dimension (:,:), allocatable :: orig_snoeb,orig_pltpst
      real, dimension (:,:), allocatable :: terr_p, terr_cn, terr_sl
      real, dimension (:,:), allocatable :: drain_d, drain_t, drain_g
      real, dimension (:,:), allocatable :: drain_idep
      real, dimension (:,:), allocatable :: cont_cn, cont_p, filt_w
      real, dimension (:,:), allocatable :: strip_n, strip_cn, strip_c
      real, dimension (:,:), allocatable :: strip_p, fire_cn
      real, dimension (:,:), allocatable :: cropno_upd,hi_upd,laimx_upd
      real, dimension (:,:,:), allocatable :: pst_lag, phug
 !!     integer, dimension (:), allocatable :: ipot,nrelease,swtrg,hrupest
      integer, dimension (:), allocatable :: nrelease,swtrg,hrupest
      integer, dimension (:), allocatable :: nro,nrot,nfert
      integer, dimension (:), allocatable :: igro,nair,ipnd1,ipnd2
      integer, dimension (:), allocatable :: nirr,iflod1,iflod2,ndtarg
      integer, dimension (:), allocatable :: iafrttyp, nstress
      integer, dimension (:), allocatable :: igrotree
      !! burn
      integer, dimension (:), allocatable :: grz_days
      integer, dimension (:), allocatable :: nmgt,icr,ncut,nsweep,nafert
      integer, dimension (:), allocatable :: irn,irrno,sol_nly,npcp
      integer, dimension (:), allocatable :: igrz,ndeat,ngr,ncf
      integer, dimension (:), allocatable :: idorm,urblu,hru_sub,ldrain
      integer, dimension (:), allocatable :: hru_seq
      integer, dimension (:), allocatable :: iurban,iday_fert,icfrt
      integer, dimension (:), allocatable :: ndcfrt,irip,ifld,hrugis
      integer, dimension (:), allocatable :: orig_igro,ntil,irrsc
      integer, dimension (:), allocatable :: iwatable,curyr_mat
      integer, dimension (:), allocatable :: ncpest,icpst,ndcpst
      integer, dimension (:), allocatable :: iday_pest, irr_flag
      integer, dimension (:), allocatable :: irra_flag
      integer, dimension (:,:), allocatable :: rndseed, iterr, iyterr
      integer, dimension (:,:), allocatable :: itdrain, iydrain, ncrops
      integer, dimension (:), allocatable :: manure_id

!!     gsm added for sdr (drainage) 7/24/08
      integer, dimension (:,:), allocatable :: mgt_sdr,idplrot
      integer, dimension (:,:), allocatable :: icont, iycont
      integer, dimension (:,:), allocatable :: ifilt, iyfilt
      integer, dimension (:,:), allocatable :: istrip, iystrip
      integer, dimension (:,:), allocatable :: iopday, iopyr, mgt_ops
      real, dimension (:), allocatable :: wshd_pstap, wshd_pstdg
      integer, dimension (:), allocatable :: ndmo,npno,mcrhru
      character(len=13), dimension (18) :: rfile,tfile
!!      character(len=1), dimension (50000) :: hydgrp, kirr  !!for srin's big run

!     character(len=4), dimension (50) :: urbname
      character(len=4), dimension (1000) :: urbname
!!      character(len=16), dimension (50000) :: snam   !! for srin's big runs

      character(len=1), dimension (:), allocatable :: hydgrp, kirr
      character(len=16), dimension (:), allocatable :: snam
      character(len=17), dimension (300) :: pname
!!    adding qtile to output.hru write 3/2/2010 gsm  increased heds(70) to heds(71)
      character(len=13) :: heds(90),hedb(24),hedr(46),hedrsv(41)
      character(len=13) :: hedwtr(40)
      character(len=4) :: title(60), cpnm(5000)
      character(len=17), dimension(50) :: fname
! measured input files
      real, dimension (:,:,:), allocatable :: flomon,solpstmon,srbpstmon
      real, dimension (:,:,:), allocatable :: sedmon,orgnmon,orgpmon
      real, dimension (:,:,:), allocatable :: no3mon,minpmon,nh3mon
      real, dimension (:,:,:), allocatable :: no2mon,bactpmon,bactlpmon
      real, dimension (:,:,:), allocatable :: cmtl1mon,cmtl2mon,cmtl3mon
      real, dimension (:,:,:), allocatable :: chlamon,disoxmon,cbodmon
      real, dimension (:,:), allocatable :: floyr,sedyr,orgnyr,orgpyr
      real, dimension (:,:), allocatable :: no3yr,minpyr,nh3yr,no2yr
      real, dimension (:,:), allocatable :: bactpyr,bactlpyr,cmtl1yr
      real, dimension (:,:), allocatable :: cmtl2yr,cmtl3yr,chlayr
      real, dimension (:,:), allocatable :: disoxyr,cbodyr,solpstyr
      real, dimension (:,:), allocatable :: srbpstyr
	real, dimension (:,:), allocatable :: sol_mc,sol_mn,sol_mp
      real, dimension (:), allocatable :: flocnst,sedcnst,orgncnst
      real, dimension (:), allocatable :: orgpcnst,no3cnst,minpcnst
      real, dimension (:), allocatable :: nh3cnst,no2cnst,bactpcnst
      real, dimension (:), allocatable :: cmtl1cnst,cmtl2cnst,bactlpcnst
      real, dimension (:), allocatable :: cmtl3cnst,chlacnst,disoxcnst
      real, dimension (:), allocatable :: cbodcnst,solpstcnst,srbpstcnst

! hourly time step (by AVG)
      integer :: idt, nstep
      real, dimension (:), allocatable :: hrtwtr,hhstor,hdepth,hsdti
      real, dimension (:), allocatable :: hrchwtr,halgae,horgn,hnh4
      real, dimension (:), allocatable :: hno2,hno3,horgp,hsolp,hbod
      real, dimension (:), allocatable :: hdisox,hchla,hsedyld,hsedst
      real, dimension (:), allocatable :: hharea,hsolpst,hsorpst
      real, dimension (:), allocatable :: hhqday,precipdt
      real, dimension (:), allocatable :: hhtime,hbactp,hbactlp
! store initial values
      integer, dimension (:), allocatable :: ivar_orig
      real, dimension (:), allocatable :: rvar_orig
! Input Uncertainty, added by Ann van Griensven
      integer ::  nauto, nsave, iatmodep
! additional reach variables , added by Ann van Griensven
        real, dimension (:), allocatable :: wattemp
! Modifications to Pesticide and Water routing routines by Balaji Narasimhan
        real, dimension (:), allocatable :: lkpst_mass, lkspst_mass
        real, dimension (:), allocatable :: vel_chan
!Additional buffer and filter strip variables Mike White
      real, dimension (:), allocatable :: vfscon,vfsratio,vfsch,vfsi
      real, dimension (:,:), allocatable :: filter_i,filter_ratio
      real, dimension (:,:), allocatable :: filter_con,filter_ch
!! sj, june 07 modifications to carbon balance routines
      real, dimension (:,:), allocatable :: sol_n
      integer :: cswat
!! sj, june 07 end

!! sj, dec 07 dynamic bulk density
      real, dimension (:,:), allocatable :: sol_bdp
!! sj dec 07 end

!! Armen Jan 08
      real, dimension (:,:), allocatable :: tillagef
      real, dimension (:), allocatable :: rtfr
      real, dimension (:), allocatable :: stsol_rd
!! Armen Jan 08 end
	integer:: urban_flag, dorm_flag
	real :: bf_flg, iabstr
	real, dimension (:), allocatable :: ubnrunoff,ubntss
	real, dimension (:,:), allocatable :: sub_ubnrunoff,sub_ubntss,
     & ovrlnd_dt
	real, dimension (:,:,:), allocatable :: hhsurf_bs

!! subdaily erosion modeling by Jaehak Jeong
	integer:: sed_ch,iuh
	real :: eros_spl, rill_mult, eros_expo, sedprev, c_factor
	real :: sig_g, ch_d50, uhalpha, abstinit,abstmax
	real, dimension(:,:), allocatable:: hhsedy, sub_subp_dt
	real, dimension(:,:), allocatable:: sub_hhsedy,sub_atmp
	real, dimension(:), allocatable:: rhy,init_abstrc
	real, dimension(:), allocatable:: dratio, hrtevp, hrttlc
	real, dimension(:,:,:), allocatable:: rchhr
!! subdaily reservoir modeling by Jaehak Jeong
	real, dimension(:), allocatable:: hhresflwi, hhresflwo,
     & hhressedi, hhressedo

!! bmp modeling by jaehak jeong
      character(len=4), dimension(:), allocatable:: lu_nodrain
      integer, dimension(:), allocatable:: bmpdrain
      real, dimension(:), allocatable :: sub_cn2, sub_ha_urb,
     & bmp_recharge
      !sed-fil
      real, dimension(:), allocatable:: sub_ha_imp,subdr_km,subdr_ickm
      real, dimension(:,:), allocatable:: sf_im,sf_iy,sp_sa,
     &  sp_pvol,sp_pd,sp_sedi,sp_sede,ft_sa,ft_fsa,
     &  ft_dep,ft_h,ft_pd,ft_k,ft_dp,ft_dc,ft_por,
     &  tss_den,ft_alp,sf_fr,sp_qi,sp_k,ft_qpnd,sp_dp,
     &  ft_qsw,ft_qin,ft_qout,ft_sedpnd,sp_bpw,ft_bpw,
     &  ft_sed_cumul,sp_sed_cumul
      integer, dimension(:), allocatable:: num_sf
      integer, dimension(:,:), allocatable:: sf_typ,sf_dim,ft_qfg,
     &  sp_qfg,sf_ptp,ft_fc

      !detention pond
	integer, dimension(:), allocatable :: dtp_subnum,dtp_imo,
     &  dtp_iyr,dtp_numweir,dtp_numstage,dtp_stagdis,
     &  dtp_reltype,dtp_onoff
!! sj & armen changes for SWAT-C
	real, dimension (:), allocatable :: cf, cfh, cfdec
!! sj & armen changes for SWAT-C end
! additional nutrient variables by jeong for montana bitterroot
      real, dimension(:), allocatable :: lat_orgn, lat_orgp

	integer, dimension(:,:), allocatable :: dtp_weirtype,dtp_weirdim

	real, dimension(:), allocatable ::dtp_evrsv,
     &  dtp_inflvol,dtp_totwrwid,dtp_lwratio,dtp_wdep,dtp_totdep,
     &  dtp_watdepact,dtp_outflow,dtp_totrel,dtp_backoff,dtp_seep_sa,
     &  dtp_evap_sa,dtp_pet_day,dtp_pcpvol,dtp_seepvol,dtp_evapvol,
     &  dtp_flowin,dtp_backup_length,dtp_intcept,dtp_expont,dtp_coef1,
     &  dtp_coef2,dtp_coef3,dtp_dummy1,dtp_dummy2,
     &  dtp_dummy3,dtp_ivol,dtp_ised

      integer, dimension (:,:),allocatable :: so_res_flag, ro_bmp_flag
      real, dimension (:,:),allocatable :: sol_watp, sol_solp_pre
	real, dimension (:,:),allocatable :: psp_store, ssp_store, so_res
	real, dimension (:,:),allocatable :: sol_cal, sol_ph
      integer:: sol_p_model
      integer, dimension (:,:),allocatable :: a_days, b_days
      real, dimension (:), allocatable :: harv_min, fstap, min_res
      real, dimension (:,:),allocatable :: ro_bmp_flo, ro_bmp_sed
      real, dimension (:,:),allocatable :: ro_bmp_bac
      real, dimension (:,:),allocatable :: ro_bmp_pp, ro_bmp_sp
      real, dimension (:,:),allocatable :: ro_bmp_pn, ro_bmp_sn

      real, dimension (:,:),allocatable :: ro_bmp_flos, ro_bmp_seds
      real, dimension (:,:),allocatable :: ro_bmp_bacs
      real, dimension (:,:),allocatable :: ro_bmp_pps, ro_bmp_sps
      real, dimension (:,:),allocatable :: ro_bmp_pns, ro_bmp_sns

      real, dimension (:,:),allocatable :: ro_bmp_flot, ro_bmp_sedt
      real, dimension (:,:),allocatable :: ro_bmp_bact
      real, dimension (:,:),allocatable :: ro_bmp_ppt, ro_bmp_spt
      real, dimension (:,:),allocatable :: ro_bmp_pnt, ro_bmp_snt

      real, dimension (:),allocatable :: bmp_flo, bmp_sed, bmp_bac
      real, dimension (:),allocatable :: bmp_pp, bmp_sp
      real, dimension (:),allocatable :: bmp_pn, bmp_sn, bmp_flag

      real, dimension (:),allocatable :: bmp_flos, bmp_seds, bmp_bacs
      real, dimension (:),allocatable :: bmp_pps, bmp_sps
      real, dimension (:),allocatable :: bmp_pns, bmp_sns

      real, dimension (:),allocatable :: bmp_flot, bmp_sedt, bmp_bact
      real, dimension (:),allocatable :: bmp_ppt, bmp_spt
      real, dimension (:),allocatable :: bmp_pnt, bmp_snt

      real, dimension(:,:), allocatable:: dtp_wdratio,dtp_depweir,
     &  dtp_diaweir,dtp_retperd,dtp_pcpret,dtp_cdis,dtp_flowrate,
     &  dtp_wrwid,dtp_addon
!!    added for manure Armen Jan 2009
 !!     real, dimension (:,:), allocatable :: sol_mc, sol_mn, sol_mp

      !retention irrigation
      real, dimension(:), allocatable:: ri_subkm,ri_totpvol,
     &  irmmdt
      real, dimension(:,:), allocatable:: ri_sed,ri_fr,ri_dim,
     &  ri_im,ri_iy,ri_sa,ri_vol,ri_qi,ri_k,ri_dd,ri_evrsv,
     &  ri_dep,ri_ndt,ri_pmpvol,ri_sed_cumul,hrnopcp,ri_qloss,
     &  ri_pumpv,ri_sedi
      character(len=4), dimension(:,:), allocatable:: ri_nirr
      integer, dimension(:), allocatable:: num_ri,ri_luflg,num_noirr

      !wet pond
      integer, dimension(:), allocatable:: wtp_subnum,wtp_onoff,wtp_imo,
     &  wtp_iyr,wtp_dim,wtp_stagdis,wtp_sdtype
      real, dimension(:), allocatable:: wtp_pvol,wtp_pdepth,wtp_sdslope,
     &  wtp_lenwdth,wtp_extdepth,wtp_hydeff,wtp_evrsv,wtp_sdintc,
     &  wtp_sdexp,wtp_sdc1,wtp_sdc2,wtp_sdc3,wtp_pdia,wtp_plen,
     &  wtp_pmann,wtp_ploss,wtp_k,wtp_dp,wtp_sedi,wtp_sede,wtp_qi

      real :: bio_init, lai_init, cnop,hi_ovr,harveff,frac_harvk

      ! van Genuchten equation's coefficients
      real, allocatable :: lid_vgcl,lid_vgcm,lid_qsurf_total,
     & lid_farea_sum

      ! soil water content and amount of accumulated infiltration
      real, dimension(:,:), allocatable :: lid_cuminf_last,
     & lid_sw_last, interval_last,lid_f_last,lid_cumr_last,lid_str_last,
     & lid_farea,lid_qsurf,lid_sw_add,lid_cumqperc_last,lid_cumirr_last,
     & lid_excum_last                                                      !! nbs

      ! Green Roof
      integer, dimension(:,:), allocatable:: gr_onoff,gr_imo,gr_iyr
      real, dimension(:,:), allocatable:: gr_farea,gr_solop,gr_etcoef,
     & gr_fc,gr_wp,gr_ksat,gr_por,gr_hydeff,gr_soldpt,gr_dummy1,
     & gr_dummy2,gr_dummy3,gr_dummy4,gr_dummy5

      ! Rain Gerden
      integer, dimension(:,:), allocatable:: rg_onoff,rg_imo,rg_iyr
      real, dimension(:,:), allocatable:: rg_farea,rg_solop,rg_etcoef,
     & rg_fc,rg_wp,rg_ksat,rg_por,rg_hydeff,rg_soldpt,rg_dimop,rg_sarea,
     & rg_vol,rg_sth,rg_sdia,rg_bdia,rg_sts,rg_orifice,rg_oheight,
     & rg_odia,rg_dummy1,rg_dummy2,rg_dummy3,rg_dummy4,rg_dummy5

      ! CiStern
      integer, dimension(:,:), allocatable:: cs_onoff,cs_imo,cs_iyr,
     & cs_grcon
      real, dimension(:,:), allocatable:: cs_farea,cs_vol,cs_rdepth,
     & cs_dummy1,cs_dummy2,cs_dummy3,cs_dummy4,cs_dummy5

      ! Porous paVement
      integer, dimension(:,:), allocatable:: pv_onoff,pv_imo,pv_iyr,
     & pv_solop
      real, dimension(:,:), allocatable:: pv_grvdep,pv_grvpor,pv_farea,
     & pv_drcoef,pv_fc,pv_wp,pv_ksat,pv_por,pv_hydeff,pv_soldpt,
     & pv_dummy1,pv_dummy2,pv_dummy3,pv_dummy4,pv_dummy5

      ! LID general
      integer, dimension(:,:), allocatable:: lid_onoff

!! By Zhang for C/N cycling
      !!SOM-residue C/N state variables -- currently included
	real, dimension(:,:), allocatable :: sol_BMC, sol_BMN, sol_HSC,
     &	sol_HSN, sol_HPC, sol_HPN, sol_LM,
     &  sol_LMC, sol_LMN, sol_LS, sol_LSL, sol_LSC, sol_LSN	, sol_RNMN,
     &  sol_LSLC, sol_LSLNC, sol_RSPC, sol_WOC, sol_WON, sol_HP, sol_HS,
     &  sol_BM
      !	HSC mass of C present in slow humus (kg ha-1)
      !	HSN mass of N present in slow humus (kg ha-1)
      !	HPC mass of C present in passive humus (kg ha-1)
      !	HPN mass of N present in passive humus (kg ha-1)
      !	LM mass of metabolic litter (kg ha-1)
      !	LMC mass of C in metabolic litter (kg ha-1)
      !	LMN mass of N in metabolic litter (kg ha-1)
      !	LS mass of structural litter (kg ha-1)
      !	LSC mass of C in structural litter (kg ha-1)
      !	LSL mass of lignin in structural litter (kg ha-1)
      !	LSN mass of N in structural litter (kg ha-1)

      !!SOM-residue C/N state variables -- may need to be included
	real, dimension(:,:), allocatable :: sol_CAC, sol_CEC

	!!daily updated soil layer associated percolaton and lateral flow Carbon loss
	real, dimension(:,:), allocatable :: sol_percc
	real, dimension(:,:), allocatable :: sol_latc

      !!Daily carbon change by different means (entire soil profile for each HRU)
	real, dimension(:), allocatable :: sedc_d, surfqc_d, latc_d,
     &	percc_d, foc_d, NPPC_d, rsdc_d, grainc_d, stoverc_d, soc_d,
     &  rspc_d, emitc_d
	!!emitc_d include biomass_c eaten by grazing, burnt

      !!Daily carbon change by different means (entire soil profile for each Subbasin)
      !!Only defined the variables, but not used them in the code
	real, dimension(:), allocatable :: sub_sedc_d, sub_surfqc_d,
     &  sub_latc_d,	sub_percc_d, sub_foc_d, sub_NPPC_d, sub_rsdc_d,
     &  sub_grainc_d, sub_stoverc_d, sub_emitc_d, sub_soc_d, sub_rspc_d

      !!Monthly carbon change by different means (entire soil profile for each HRU)
	real, dimension(:), allocatable :: sedc_m, surfqc_m, latc_m, percc_m,
     &  foc_m, NPPC_m, rsdc_m, grainc_m, stoverc_m, emitc_m, soc_m,
     &  rspc_m

      !!Yearly carbon change by different means (entire soil profile for each HRU)
	real, dimension(:), allocatable :: sedc_a, surfqc_a, latc_a,
     &  percc_a, foc_a, NPPC_a, rsdc_a, grainc_a, stoverc_a, emitc_a,
     &  soc_a, rspc_a

      !! The following variables are defined and calculated locally
      !! ==================================================================
      !	HSCTP potential transformation of C in slow humus (kg ha-1 day-1)
      !	HSNTP potential transformation of N in slow humus (kg ha.1 day-1)
      !	HPCTP potential transformation of C in passive humus (kg ha-1 day-1)
      !	HPNTP potential transformation of N in passive humus (kg ha-1 day-1)
      !	HPR rate of transformation of passive humus under optimal conditions (subsurface
      !	layers = 0.000012 day-1) (Parton et al.,1993, 1994)
      !	HSR rate of transformation of slow humus under optimal conditions (all layers
      !	= 0.0005 day.1) (Parton et al., 1993, 1994; Vitousek et al., 1993)
      !	KOC liquid C solid partition coefficient for microbial biomass (10^3 m3 Mg-1)
      !	LMF fraction of the litter that is metabolic
      !	LMNF fraction of metabolic litter that is N (kg kg-1)
      !	LMR rate of transformation of metabolic litter under optimal conditions (surface =
      !	 0.0405 day-1; all other layers = 0.0507 day-1) (Parton et al., 1994)
      !	LMCTP potential transformation of C in metabolic litter (kg ha-1 day-1)
      !	LMNTP potential transformation of N in metabolic litter (kg ha-1 day-1)
      !	LSCTP potential transformation of C in structural litter (kg ha-1 day-1)
      !	LSF fraction of the litter that is structural
      !	LSLF fraction of structural litter that is lignin (kg kg-1)
      !	LSNF fraction of structural litter that is N (kg kg-1)
      !	LSLCTP potential transformation of C in lignin of structural litter (kg ha-1 day-1)
      !	LSLNCTP potential transformation of C in nonlignin structural litter (kg ha-1 day-1)
      !	LSNTP potential transformation of N in structural litter (kg ha-1 day-1)
      !	LSR rate of potential transformation of structural litter under optimal conditions
      !	(surface = 0.0107 day.1; all other layers = 0.0132 day.1) (Parton et al., 1994)
      !	NCBM N/C ratio of biomass
      !	NCHP N/C ratio passive humus
      !	NCHS N/C ratio of the slow humus
      !	OX oxygen control on biological processes with soil depth
      !	Sf fraction of mineral N sorbed to litter: 0.05 for surface litter, 0.1 for belowground litter

      !!Tillage factor on SOM decomposition
      integer, dimension(:), allocatable :: tillage_switch
      real, dimension(:), allocatable :: tillage_depth
      integer, dimension(:), allocatable :: tillage_days
      real, dimension(:), allocatable :: tillage_factor
      ! tillage_factor: = 1.6 in 30 days after tillage practices occur; otherwise 1.0;
!! By Zhang for C/N cycling

      !!GWP edits for soil water changes
      integer :: iperc, iwriteperc ! flags
      ! can use these for debugging
      real, dimension(:,:), allocatable :: sol_sepp, sol_exw, sol_ule
      real, dimension (:,:), allocatable :: sol_dg, sol_sep, sol_lat
      real, dimension (:,:), allocatable :: infl_print
      !Parameters for PTFs
      real, dimension(:,:), allocatable :: wo_thr,
     &  rb_thr, ca_rb_b, vg_rb_m, ca_co_b, vg_co_m,
     &  ca_sx_b, vg_sx_m, ca_wo_b, vg_wo_m
      real, dimension(:,:), allocatable :: vswc
!!    End GWP edits

      end module parm